package org.log4jconfig.xml.editor.utils;

import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.part.FileEditorInput;

@SuppressWarnings("restriction")
public class JdtUtils {

	/**
	 * Retrieve the JavaProject the current edited resource belongs to
	 * @return instance of IJavaProject containing the edited resource
	 */
	public static final IJavaProject getCurrentJavaProject() {
		IJavaProject javaProject = null;
		IEditorInput input = Workbench.getInstance().getActiveWorkbenchWindow()
				.getActivePage().getActiveEditor().getEditorInput();
		if (input instanceof FileEditorInput) {
			IProject project = ((FileEditorInput) input).getFile().getProject();
			javaProject = (JavaProject) JavaCore.create(project);
		}
		return javaProject;
	}
	
	/**
	 * Returns the IType given its fully qualified name, found in the current java project's classpath
	 * @param fullyQualifiedName
	 * @return the instance of IType
	 * @throws JavaModelException
	 */
	public static final IType getTypeFromCurrentProject(String fullyQualifiedName) throws JavaModelException {
		IJavaProject javaProject = getCurrentJavaProject();
		return javaProject.findType(fullyQualifiedName);
	}

	public static String getPackageFromQualifiedName(
			String name) {
		if(name == null || name.equals("") || name.equals(".")) {
			return "";
		} 
		if(name.charAt(name.length()-1) == '.') {
			return  name.substring(0, name.length()-1);
		} else {
			int lastDotIndex = name.lastIndexOf('.');
			// if next char is uppercase, then it is the beginning of a className (according to Java coding conventions)
			if(lastDotIndex == -1 && Character.isUpperCase(name.charAt(0))) {
				return "";
			}
			else if(lastDotIndex == -1 && !Character.isUpperCase(name.charAt(0))) {
				return name;
			}
			else if(Character.isUpperCase(name.charAt(lastDotIndex + 1))) {
				return name.substring(0, lastDotIndex);
			} 
		}
		return name;
		
	}

}
